#include <iostream>
#include <list>
#include "SDL/SDL.h"
#include "SDL/SDL_opengl.h"
#include "SDL/SDL_mixer.h"
#include "pathFinding.h"
#include "pathNode.h"
#include "commonFunc.h"
#include "tower.h"
#include "unit.h"
#include "mouse.h"
#include "missle.h"
#include "player.h"
#include "globaldef.h"
#include "gui.h"
#include "ptrContainer.h"
#include "particle.h"
#include "textparticle.h"
#include "states/stateincludes.h"

using namespace std;



int main(int argc, char** argv)
{
    populateStaticVars();
    //INIT DATA CONTAINER
    ptrContainer dcontainer;

    //terribad player health and damage
    int spawns = 1;
    player theplayer;
    dcontainer.theplayer = &theplayer;
    theplayer.maxhp = 10;
    theplayer.curhp = 10;
    theplayer.cash = 8;

    //INIT PATH FINDING
    Path* p = new Path(32,22);
    dcontainer.p = p;

    //INIT MOUSE
    mouse m(32,22);
    dcontainer.m = &m;

    //INIT openGL
    initScreen(dcontainer);

    //UNIT LISTS
    list<tower*> towerlist;
    list<unit*> unitlist;
    list<missle*> misslelist;
    list<particle*> particlelist;
    dcontainer.towerlist = &towerlist;
    dcontainer.unitlist = &unitlist;
    dcontainer.misslelist = &misslelist;
    dcontainer.particlelist = &particlelist;
    
    //This loads all the textures
    GLuint bgint = genTexArr(dcontainer);
    dcontainer.bg = &bgint;

    //INIT gui
    gui* g = new gui(theplayer);
    dcontainer.g = g;

    //This is a control variable, when cont = false the game ends
    bool cont = true;

    statewrapper sw(&dcontainer);

    dcontainer.sw = &sw;

    //get initial time at start of loop
    int ticktime = SDL_GetTicks();
    int endtime = SDL_GetTicks();
    int drawtime = SDL_GetTicks();
    bool passed = false;
    while(cont)
    {
        //START FRAMERATE
        int starttime = SDL_GetTicks();

        cont = sw.update(endtime, ticktime);
        sw.draw(drawtime);
        
        //HANDLE FRAMERATE
        if ((endtime-starttime) < (1000 / FRAMES_PER_SECOND))
        {
            SDL_Delay((1000/FRAMES_PER_SECOND)-(endtime-starttime));
        }
    }

    //CLEAN UP
    SDL_SetVideoMode( 1024, 768, 32, SDL_OPENGL);


    //clear audio
    for (unsigned int x = 0; x < NUMOFSOUNDS; x++)
        Mix_FreeChunk(dcontainer.sounds[x]);
    Mix_CloseAudio();

    //clear textures
    glDeleteTextures(1, &bgint);
    glDeleteTextures(1, &unit::tex);
    glDeleteTextures(1, &unit2::tex);
    glDeleteTextures(1, &gui::tex);
    glDeleteTextures(10, gui::numarr);

    delete p;
    delete g;
    SDL_Quit();
}
